﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin.Win32;
using ERPWinFormWork.Produce.ErrorCode;
using static System.Windows.Forms.AxHost;
using static ERPWinFormWork.Produce.Dispatch_WorkForm;

namespace ERPWinFormWork.Produce
{
    public partial class Report_QualityForm : Form
    {
        private ApiClient _apiClient;
        public bool IsOperationCompletedss { get; internal set; }
        public Report_QualityForm()
        {
            InitializeComponent();
            this._apiClient = _apiClient;
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            LoadcboStatesData();
            LoadcboQuality_DepartmentData();
            LoadcboQuality_InspectorsData();

        }

        public class CreateReport_QualityModel
        {
            /// <summary>
            /// 检验单名称
            /// </summary>
            public string Inspection_Name { get; set; }
            /// <summary>
            /// 检验单编号
            /// </summary>
            public string Inspection_Number { get; set; }
            /// <summary>
            /// 检验时间
            /// </summary>
            public DateTime Inspection_Time { get; set; }
            /// <summary>
            /// 检验类型
            /// </summary>
            public string Inspection_Type { get; set; }
            /// <summary>
            /// 检验部门
            /// </summary>
            public string Inspection_Department { get; set; }
            /// <summary>
            /// 检验人
            /// </summary>
            public string Inspector { get; set; }
            /// <summary>
            /// 检验数量
            /// </summary>
            public int Inspection_Quantity { get; set; }
            /// <summary>
            /// 致命缺陷数量
            /// </summary>
            public int Number_Fatal { get; set; }
            /// <summary>
            /// 严重缺陷数量
            /// </summary>
            public int Number_Serious { get; set; }
            /// <summary>
            /// 轻微缺陷数量
            /// </summary>
            public int Number_Minor { get; set; }
            /// <summary>
            /// 致命缺陷率
            /// </summary>
            public decimal Fatal_Rate { get; set; }
            /// <summary>
            /// 严重缺陷率
            /// </summary>
            public decimal Serious_Rate { get; set; }
            /// <summary>
            /// 轻微缺陷率
            /// </summary>
            public decimal Minor_Rate { get; set; }
            /// <summary>
            /// 合格数量
            /// </summary>
            public int Qualified_Quantity { get; set; }
            /// <summary>
            /// 不合格数量
            /// </summary>
            public int Unqualified_Quantity { get; set; }
            /// <summary>
            /// 合格率
            /// </summary>
            public decimal Pass_Rate { get; set; }
            /// <summary>
            /// 检验结果
            /// </summary>
            public string Inspection_Results { get; set; }
            /// <summary>
            /// 状态
            /// </summary>
            public bool State { get; set; }
            /// <summary>
            /// 备注(基础)
            /// </summary>
            public string Basic_Remarks { get; set; }
            /// <summary>
            /// 备注(检测)
            /// </summary>
            public string Testing_Remarks { get; set; }

            /// <summary>
            /// 结果
            /// </summary>
            public string Result { get; set; }
        }

        private void LoadcboStatesData()
        {
            // 模拟一个数据源，这里是简单的字符串列表，实际可从数据库等获取
            List<string> addressList = new List<string>()
            {
                "首检",
                "末检",
                "自检",
                "其他",

            };

            // 清空ComboBox原有项（可选，避免重复添加）
            cboInspection_Type.Items.Clear();
            // 将数据源的数据添加到ComboBox中
            cboInspection_Type.Items.AddRange(addressList.ToArray());

            // 可选：设置默认选中项，比如选第一个
            if (cboInspection_Type.Items.Count > 0)
            {
                cboInspection_Type.SelectedIndex = -1;
            }
        }


        private void label2_Click(object sender, EventArgs e)
        {

        }

        //private async void btncreatesubmit_Click(object sender, EventArgs e)
        //{
        //    // 构建请求实体对象，将窗体控件值赋值给实体属性
        //    var requestModel = new CreateReport_QualityModel
        //    {
        //        Inspection_Name = txtInspection_Name.Text.Trim(),
        //        Inspection_Number = txtInspection_Number.Text.Trim(),
        //        Inspection_Time = dtpInspection_Time.Value,
        //        Inspection_Type = cboInspection_Type.Text.Trim(),
        //        Inspection_Department = cboQuality_Department.Text.Trim(),
        //        Inspector = cboQuality_Inspectors.Text.Trim(),
        //        Inspection_Quantity = int.TryParse(txtInspection_Quantity.Text.Trim(), out int Inspection_Quantity) ? Inspection_Quantity : 0,
        //        Number_Fatal = int.TryParse(txtNumber_Fatal.Text.Trim(), out int Number_Fatal) ? Number_Fatal : 0,
        //        Number_Serious = int.TryParse(txtNumber_Serious.Text.Trim(), out int Number_Serious) ? Number_Serious : 0,
        //        Number_Minor = int.TryParse(txtNumber_Minor.Text.Trim(), out int Number_Minor) ? Number_Minor : 0,
        //        Fatal_Rate = decimal.TryParse(txtFatal_Rate.Text.Trim(), out decimal Fatal_Rate) ? Fatal_Rate : 0,
        //        Serious_Rate = decimal.TryParse(txtSerious_Rate.Text.Trim(), out decimal Serious_Rate) ? Serious_Rate : 0,
        //        Minor_Rate = decimal.TryParse(txtMinor_Rate.Text.Trim(), out decimal Minor_Rate) ? Minor_Rate : 0,
        //        Qualified_Quantity = int.TryParse(txtQualified_Quantity.Text.Trim(), out int Qualified_Quantity) ? Qualified_Quantity : 0,
        //        Unqualified_Quantity = int.TryParse(txtUnqualified_Quantity.Text.Trim(), out int Unqualified_Quantity) ? Unqualified_Quantity : 0,
        //        Pass_Rate = decimal.TryParse(txtPass_Rate.Text.Trim(), out decimal passRate) ? passRate : 0,
        //        Inspection_Results = txtResult.Text.Trim(),
        //        State = true,
        //        Basic_Remarks = txtBasic_Remarks.Text.Trim(),
        //        Testing_Remarks = txtTesting_Remarks.Text.Trim(),
        //        Result = txtResult.Text.Trim(),
        //    };
        //    var response = await _apiClient.PostAsync<CreateReport_QualityModel, ApiResponse<string>>(
        //        endpoint: "Production_Plan/CreateReport_QualityHandle",
        //        data: requestModel
        //    );
        //    if (response.code == 200)
        //    {
        //        // 这里可根据后端返回的结果做相应处理，比如简单提示成功
        //        MessageBox.Show("质检成功");
        //        // 可选择清空窗体控件内容，准备下次添加
        //        ClearControls();
        //        IsOperationCompletedss = true;


        //        this.Close();
        //    }
        //    else
        //    {
        //        MessageBox.Show("质检失败");
        //    }
        //}





        // 清空窗体控件内容的方法，按需使用







        private async void btncreatesubmit_Click(object sender, EventArgs e)
        {

            // 先解析基础数值，方便后续计算
            int inspectionQuantity = int.TryParse(txtInspection_Quantity.Text.Trim(), out int iq) ? iq : 0;
            int qualifiedQuantity = int.TryParse(txtQualified_Quantity.Text.Trim(), out int qq) ? qq : 0;

            // 计算合格率：Qualified_Quantity / Inspection_Quantity
            // 处理除数为0的情况，避免出现异常
            decimal passRate = 0;
            if (inspectionQuantity > 0)
            {
                // 转换为decimal再计算，避免整数除法导致精度丢失
                passRate = (decimal)qualifiedQuantity/inspectionQuantity;
                // 可以根据需要保留小数位数，例如保留两位小数
                passRate = Math.Round(passRate, 4); // 保留4位小数，便于转换为百分比显示
            }
            else
            {
                // 可以添加提示，告知用户检验数量不能为0
                MessageBox.Show("检验数量不能为0，无法计算合格率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return; // 如果检验数量为0，终止提交
            }

            // 先解析基础数值，方便后续计算
            int number_Fatal = int.TryParse(txtNumber_Fatal.Text.Trim(), out int Number_Fatal) ? Number_Fatal : 0;
          

            // 计算合格率：Qualified_Quantity / Inspection_Quantity
            // 处理除数为0的情况，避免出现异常
            decimal Fatal_Rate = 0;
            if (inspectionQuantity > 0)
            {
                // 转换为decimal再计算，避免整数除法导致精度丢失
                Fatal_Rate = (decimal)number_Fatal / inspectionQuantity;
                // 可以根据需要保留小数位数，例如保留两位小数
                Fatal_Rate = Math.Round(Fatal_Rate, 4); // 保留4位小数，便于转换为百分比显示
            }
            else
            {
                // 可以添加提示，告知用户检验数量不能为0
                MessageBox.Show("致命缺陷数量不能为0，无法计算致命缺陷率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return; // 如果检验数量为0，终止提交
            }




            // 先解析基础数值，方便后续计算
            int number_Serious = int.TryParse(txtNumber_Serious.Text.Trim(), out int Number_Serious) ? Number_Serious : 0;
           

            // 计算合格率：Qualified_Quantity / Inspection_Quantity
            // 处理除数为0的情况，避免出现异常
            decimal Serious_Rate = 0;
            if (inspectionQuantity > 0)
            {
                // 转换为decimal再计算，避免整数除法导致精度丢失
                Serious_Rate = (decimal)number_Serious / inspectionQuantity;
                // 可以根据需要保留小数位数，例如保留两位小数
                Serious_Rate = Math.Round(Serious_Rate, 4); // 保留4位小数，便于转换为百分比显示
            }
            else
            {
                // 可以添加提示，告知用户检验数量不能为0
                MessageBox.Show("严重缺陷数量不能为0，无法计算严重缺陷率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return; // 如果检验数量为0，终止提交
            }



            // 先解析基础数值，方便后续计算
            int number_Minor = int.TryParse(txtNumber_Minor.Text.Trim(), out int Number_Minor) ? Number_Minor : 0;
           

            // 计算合格率：Qualified_Quantity / Inspection_Quantity
            // 处理除数为0的情况，避免出现异常
            decimal Minor_Rate = 0;
            if (inspectionQuantity > 0)
            {
                // 转换为decimal再计算，避免整数除法导致精度丢失
                Minor_Rate = (decimal)number_Minor / inspectionQuantity;
                // 可以根据需要保留小数位数，例如保留两位小数
                Minor_Rate = Math.Round(Minor_Rate, 4); // 保留4位小数，便于转换为百分比显示
            }
            else
            {
                // 可以添加提示，告知用户检验数量不能为0
                MessageBox.Show("轻微缺陷数量不能为0，无法计算轻微缺陷率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return; // 如果检验数量为0，终止提交
            }







            // 构建请求实体对象，将窗体控件值赋值给实体属性
            var requestModel = new CreateReport_QualityModel
            {
                Inspection_Name = txtInspection_Name.Text.Trim(),
                Inspection_Number = txtInspection_Number.Text.Trim(),
                Inspection_Time = dtpInspection_Time.Value,
                Inspection_Type = cboInspection_Type.Text.Trim(),
                Inspection_Department = cboQuality_Department.Text.Trim(),
                Inspector = cboQuality_Inspectors.Text.Trim(),
                Inspection_Quantity = inspectionQuantity,
                Number_Fatal = number_Fatal,
                Number_Serious = number_Serious,
                Number_Minor = number_Minor,
                Fatal_Rate = Fatal_Rate,
                Serious_Rate = Serious_Rate,
                Minor_Rate = Minor_Rate,
                Qualified_Quantity = qualifiedQuantity,
                Unqualified_Quantity = int.TryParse(txtUnqualified_Quantity.Text.Trim(), out int Unqualified_Quantity) ? Unqualified_Quantity : 0,
                Pass_Rate = passRate,
                Inspection_Results = txtResult.Text.Trim(),
                State = true,
                Basic_Remarks = txtBasic_Remarks.Text.Trim(),
                Testing_Remarks = txtTesting_Remarks.Text.Trim(),
                Result = txtResult.Text.Trim(),
            };
            var response = await _apiClient.PostAsync<CreateReport_QualityModel, ApiResponse<string>>(
                endpoint: "Production_Plan/CreateReport_QualityHandle",
                data: requestModel
            );
            if (response.code == 200)
            {
                // 这里可根据后端返回的结果做相应处理，比如简单提示成功
                MessageBox.Show("质检成功");
                // 可选择清空窗体控件内容，准备下次添加
               
                IsOperationCompletedss = true;


                this.Close();
                    
            }
            else
            {
                MessageBox.Show("质检失败");
            }
        }
















        private void ClearControls()
        {
            txtInspection_Name.Clear();
            txtInspection_Number.Clear();
            dtpInspection_Time.Value = DateTime.Now;
            cboInspection_Type.SelectedIndex = -1;
            cboQuality_Department.SelectedIndex = -1;
            cboQuality_Inspectors.SelectedIndex = -1;
            txtInspection_Quantity.Clear();
            txtNumber_Fatal.Clear();
            txtNumber_Serious.Clear();
            txtNumber_Minor.Clear();
            txtFatal_Rate.Clear();
            txtSerious_Rate.Clear();
            txtMinor_Rate.Clear();
            txtQualified_Quantity.Clear();
            txtUnqualified_Quantity.Clear();
            txtPass_Rate.Clear();
            txtResult.Clear();
            txtBasic_Remarks.Text.Clone();
            txtTesting_Remarks.Text.Clone();
            txtResult.Clear();
        }

        private void LoadcboQuality_DepartmentData()
        {
            // 模拟一个数据源，这里是简单的字符串列表，实际可从数据库等获取
            List<string> addressList = new List<string>()
            {
                "质检部门一",
                "质检部门二",
                "质检部门三",

            };

            // 清空ComboBox原有项（可选，避免重复添加）
            cboQuality_Department.Items.Clear();
            // 将数据源的数据添加到ComboBox中
            cboQuality_Department.Items.AddRange(addressList.ToArray());

            // 可选：设置默认选中项，比如选第一个
            if (cboQuality_Department.Items.Count > 0)
            {
                cboQuality_Department.SelectedIndex = -1;
            }
        }

        private void LoadcboQuality_InspectorsData()
        {
            // 模拟一个数据源，这里是简单的字符串列表，实际可从数据库等获取
            List<string> addressList = new List<string>()
            {
                "唐灵波",
                "池雅丽",
                "童芳洁",
                "昌新之",
                "禾和煦",
                "通湘云",
                "司空倚",
            };

            // 清空ComboBox原有项（可选，避免重复添加）
            cboQuality_Inspectors.Items.Clear();
            // 将数据源的数据添加到ComboBox中
            cboQuality_Inspectors.Items.AddRange(addressList.ToArray());

            // 可选：设置默认选中项，比如选第一个
            if (cboQuality_Inspectors.Items.Count > 0)
            {
                cboQuality_Inspectors.SelectedIndex = -1;
            }
        }
        //合格率
        private void txtQualified_Quantity_TextChanged(object sender, EventArgs e)
        {
            
            int qualifiedQuantity = int.TryParse(txtQualified_Quantity.Text.Trim(), out int qq) ? qq : 0;
            int inspectionQuantity = int.TryParse(txtInspection_Quantity.Text.Trim(), out int iq) ? iq : 0;

            decimal rate = (decimal)qualifiedQuantity / inspectionQuantity * 100;
             string passRate = $"{rate:F2}%";


            txtPass_Rate.Text = passRate;
        }
        //致命率
        private void txtNumber_Fatal_TextChanged(object sender, EventArgs e)
        {
            int number_Fatal = int.TryParse(txtNumber_Fatal.Text.Trim(), out int Number_Fatal) ? Number_Fatal : 0;
            int inspectionQuantity = int.TryParse(txtInspection_Quantity.Text.Trim(), out int iq) ? iq : 0;

            decimal rate = (decimal)number_Fatal / inspectionQuantity * 100;
            string fatal_Rate = $"{rate:F2}%";

            txtFatal_Rate.Text = fatal_Rate;
        }

        private void txtFatal_Rate_TextChanged(object sender, EventArgs e)
        {
          
        }
        //严重率
        private void txtNumber_Serious_TextChanged(object sender, EventArgs e)
        {
            int number_Serious = int.TryParse(txtNumber_Serious.Text.Trim(), out int Number_Serious) ? Number_Serious : 0;
            int inspectionQuantity = int.TryParse(txtInspection_Quantity.Text.Trim(), out int iq) ? iq : 0;

            decimal rate = (decimal)number_Serious / inspectionQuantity * 100;
            string Serious_Rate = $"{rate:F2}%";
            txtSerious_Rate.Text = Serious_Rate;
        }
        private void txtSerious_Rate_TextChanged(object sender, EventArgs e)
        {
           
        }
        //轻微率
        private void txtNumber_Minor_TextChanged(object sender, EventArgs e)
        {

            int number_Minor = int.TryParse(txtNumber_Minor.Text.Trim(), out int Number_Minor) ? Number_Minor : 0;
            int inspectionQuantity = int.TryParse(txtInspection_Quantity.Text.Trim(), out int iq) ? iq : 0;

            decimal rate = (decimal)number_Minor / inspectionQuantity * 100;
            string Minor_Rate = $"{rate:F2}%";
            txtMinor_Rate.Text = Minor_Rate;
        }
        private void txtMinor_Rate_TextChanged(object sender, EventArgs e)
        {
        }

       
    }
}
